//
//  UIImage+Style.m
//  ZhaoCaiMao
//
//  Created by xieyingze on 2017/3/13.
//  Copyright © 2017年 谢英泽. All rights reserved.
//

#import "UIImage+Style.h"
#import <Accelerate/Accelerate.h>

@implementation UIImage (Style)

#pragma mark - Blur高斯模糊

/**
 CoreImage.framework

 @param image 需要高斯模糊图片
 @param blur 高斯模糊系数
 @return 高斯模糊后的图片
 */
+ (UIImage *)imageWithCoreBlurImage:(UIImage *)image withBlurNumber:(CGFloat)blur {
    CIContext *context = [CIContext contextWithOptions:nil];
    CIImage  *inputImage=[CIImage imageWithCGImage:image.CGImage];
    //设置filter
    CIFilter *filter = [CIFilter filterWithName:@"CIGaussianBlur"];
    [filter setValue:inputImage forKey:kCIInputImageKey];
    [filter setValue:@(blur) forKey: @"inputRadius"];
    //模糊图片
    CIImage *result=[filter valueForKey:kCIOutputImageKey];
    CGImageRef outImage=[context createCGImage:result fromRect:[result extent]];
    UIImage *blurImage=[UIImage imageWithCGImage:outImage];
    CGImageRelease(outImage);
    return blurImage;
}

/**
 Accelerate.Framework

 @param image 需要高斯模糊图片
 @param blur 高斯模糊系数
 @return 高斯模糊后的图片
 */
+ (UIImage *)imageWithBoxblurImage:(UIImage *)image withBlurNumber:(CGFloat)blur {
    if (blur < 0.f || blur > 1.f) {
        blur = 0.5f;
    }
    int boxSize = (int)(blur * 40);
    boxSize = boxSize - (boxSize % 2) + 1;
    
    CGImageRef img = image.CGImage;
    
    vImage_Buffer inBuffer, outBuffer;
    vImage_Error error;
    
    void *pixelBuffer;
    //从CGImage中获取数据
    CGDataProviderRef inProvider = CGImageGetDataProvider(img);
    CFDataRef inBitmapData = CGDataProviderCopyData(inProvider);
    //设置从CGImage获取对象的属性
    inBuffer.width = CGImageGetWidth(img);
    inBuffer.height = CGImageGetHeight(img);
    inBuffer.rowBytes = CGImageGetBytesPerRow(img);
    
    inBuffer.data = (void*)CFDataGetBytePtr(inBitmapData);
    
    pixelBuffer = malloc(CGImageGetBytesPerRow(img) *
                         CGImageGetHeight(img));
    
    if(pixelBuffer == NULL)
        NSLog(@"No pixelbuffer");
    
    outBuffer.data = pixelBuffer;
    outBuffer.width = CGImageGetWidth(img);
    outBuffer.height = CGImageGetHeight(img);
    outBuffer.rowBytes = CGImageGetBytesPerRow(img);
    
    error = vImageBoxConvolve_ARGB8888(&inBuffer, &outBuffer, NULL, 0, 0, boxSize, boxSize, NULL, kvImageEdgeExtend);
    
    if (error) {
        NSLog(@"error from convolution %ld", error);
    }
    
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef ctx = CGBitmapContextCreate(
                                             outBuffer.data,
                                             outBuffer.width,
                                             outBuffer.height,
                                             8,
                                             outBuffer.rowBytes,
                                             colorSpace,
                                             kCGImageAlphaNoneSkipLast);
    CGImageRef imageRef = CGBitmapContextCreateImage (ctx);
    UIImage *returnImage = [UIImage imageWithCGImage:imageRef];
    
    //clean up
    CGContextRelease(ctx);
    CGColorSpaceRelease(colorSpace);
    
    free(pixelBuffer);
    CFRelease(inBitmapData);
    
    CGColorSpaceRelease(colorSpace);
    CGImageRelease(imageRef);
    
    return returnImage;
}

#pragma mark - 根据颜色值生成图片

+ (UIImage*)imageWithColor:(UIColor*)color {
    CGRect rect=CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
}

#pragma mark - 圆角处理

// 自定义裁剪算法
- (UIImage *)imageWithDealImage:(UIImage *)image cornerRadius:(CGFloat)cornerRadius {
    // 1.CGDataProviderRef 把 CGImage 转 二进制流
    CGDataProviderRef provider = CGImageGetDataProvider(image.CGImage);
    void *imgData = (void *)CFDataGetBytePtr(CGDataProviderCopyData(provider));
    int width = image.size.width * image.scale;
    int height = image.size.height * image.scale;
    
    // 2.处理 imgData
    //    dealImage(imgData, width, height);
    cornerImage(imgData, width, height, cornerRadius);
    
    // 3.CGDataProviderRef 把 二进制流 转 CGImage
    CGDataProviderRef pv = CGDataProviderCreateWithData(NULL, imgData, width * height * 4, releaseData);
    CGImageRef content = CGImageCreate(width , height, 8, 32, 4 * width, CGColorSpaceCreateDeviceRGB(), kCGBitmapByteOrder32Big | kCGImageAlphaPremultipliedLast, pv, NULL, true, kCGRenderingIntentDefault);
    UIImage *result = [UIImage imageWithCGImage:content];
    CGDataProviderRelease(pv);      // 释放空间
    CGImageRelease(content);
    
    return result;
}

void releaseData(void *info, const void *data, size_t size) {
    free((void *)data);
}

// 裁剪圆角
void cornerImage(UInt32 *const img, int w, int h, CGFloat cornerRadius) {
    CGFloat c = cornerRadius;
    CGFloat min = w > h ? h : w;
    
    if (c < 0) { c = 0; }
    if (c > min * 0.5) { c = min * 0.5; }
    
    // 左上 y:[0, c), x:[x, c-y)
    for (int y=0; y<c; y++) {
        for (int x=0; x<c-y; x++) {
            UInt32 *p = img + y * w + x;    // p 32位指针，RGBA排列，各8位
            if (isCircle(c, c, c, x, y) == false) {
                *p = 0;
            }
        }
    }
    // 右上 y:[0, c), x:[w-c+y, w)
    int tmp = w-c;
    for (int y=0; y<c; y++) {
        for (int x=tmp+y; x<w; x++) {
            UInt32 *p = img + y * w + x;
            if (isCircle(w-c, c, c, x, y) == false) {
                *p = 0;
            }
        }
    }
    // 左下 y:[h-c, h), x:[0, y-h+c)
    tmp = h-c;
    for (int y=h-c; y<h; y++) {
        for (int x=0; x<y-tmp; x++) {
            UInt32 *p = img + y * w + x;
            if (isCircle(c, h-c, c, x, y) == false) {
                *p = 0;
            }
        }
    }
    // 右下 y~[h-c, h), x~[w-c+h-y, w)
    tmp = w-c+h;
    for (int y=h-c; y<h; y++) {
        for (int x=tmp-y; x<w; x++) {
            UInt32 *p = img + y * w + x;
            if (isCircle(w-c, h-c, c, x, y) == false) {
                *p = 0;
            }
        }
    }
}

// 判断点 (px, py) 在不在圆心 (cx, cy) 半径 r 的圆内
static inline bool isCircle(float cx, float cy, float r, float px, float py) {
    if ((px-cx) * (px-cx) + (py-cy) * (py-cy) > r * r) {
        return false;
    }
    return true;
}

// 其他图像效果可以自己写函数，然后在 dealImage: 中调用 otherImage 即可
void otherImage(UInt32 *const img, int w, int h) {
    // 自定义处理
}

#pragma mark - 根据银行卡名称获取图片

+ (UIImage *)imageWithBankName:(NSString *)bankName {
    
    //    for (NSString *key in _bankDic) {
    //        NSString *bank = [key substringToIndex:2];
    //        NSRange range = [bankName rangeOfString:bank];
    //        if (range.location != NSNotFound) {
    //            imgStr = key;
    //            break;
    //        }
    //    }
    
    NSString *imgStr = nil;
    if (bankName == nil || bankName.length == 0) {
        return [UIImage imageNamed:imgStr?imgStr:@"wt_bank_default"];
    }
    
    if ([bankName rangeOfString:@"北京"].location != NSNotFound) {
        imgStr = @"wt_bank_beijin";
    }else if ([bankName rangeOfString:@"工商"].location != NSNotFound){
        imgStr = @"wt_bank_gongshang";
    }else if ([bankName rangeOfString:@"光大"].location != NSNotFound){
        imgStr = @"wt_bank_guangda";
    }else if ([bankName rangeOfString:@"广发"].location != NSNotFound){
        imgStr = @"wt_bank_guangfa";
    }else if ([bankName rangeOfString:@"华夏"].location != NSNotFound){
        imgStr = @"wt_bank_huaxia";
    }else if ([bankName rangeOfString:@"建设"].location != NSNotFound){
        imgStr = @"wt_bank_jianshe";
    }else if ([bankName rangeOfString:@"交通"].location != NSNotFound){
        imgStr = @"wt_bank_jiaotong";
    }else if ([bankName rangeOfString:@"民生"].location != NSNotFound){
        imgStr = @"wt_bank_minsheng";
    }else if ([bankName rangeOfString:@"农业"].location != NSNotFound){
        imgStr = @"wt_bank_nongye";
    }else if ([bankName rangeOfString:@"平安"].location != NSNotFound){
        imgStr = @"wt_bank_pingan";
    }else if ([bankName rangeOfString:@"浦发"].location != NSNotFound ||
              [bankName rangeOfString:@"浦东发展"].location != NSNotFound){
        imgStr = @"wt_bank_pufa";
    }else if ([bankName rangeOfString:@"上海银行"].location != NSNotFound){
        imgStr = @"wt_bank_shanghai";
    }else if ([bankName rangeOfString:@"兴业"].location != NSNotFound){
        imgStr = @"wt_bank_xingye";
    }else if ([bankName rangeOfString:@"邮政"].location != NSNotFound){
        imgStr = @"wt_bank_youzheng";
    }else if ([bankName rangeOfString:@"招商"].location != NSNotFound){
        imgStr = @"wt_bank_zhaoshang";
    }else if ([bankName rangeOfString:@"中国银行"].location != NSNotFound){
        imgStr = @"wt_bank_zhongguo";
    }else if ([bankName rangeOfString:@"中信"].location != NSNotFound){
        imgStr = @"wt_bank_zhongxin";
    }
    
    
    UIImage *image = [UIImage imageNamed:imgStr?imgStr:@"wt_bank_default"];
    return image;
}

@end
